package com.lgt_enterprise_android.view.pages.b;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lgt_enterprise_android.Constant;
import com.lgt_enterprise_android.R;
import com.lgt_enterprise_android.base.BaseActivity;
import com.lgt_enterprise_android.utils.BasicHttp;
import com.lgt_enterprise_android.utils.CommonUtil;
import com.lgt_enterprise_android.utils.HttpManager;
import com.lgt_enterprise_android.utils.StringUtil;
import com.lgt_enterprise_android.view.widgets.weekcalendar.DateAdapter;
import com.lgt_enterprise_android.view.widgets.weekcalendar.DateBean;
import com.util.AppUtil;
import com.widgets.CustomizeTitleView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

public class ArrangeJobActivity extends BaseActivity {
    CustomizeTitleView customizeTitleView;
    private LinearLayout linLeft;
    private LinearLayout linTable;
    private LinearLayout linRightDialog;
    private FrameLayout linTimeLine;

    private float mDPI;

    private int gridWidth;
    private float perSeekWidth, perSeekWidth1;

    private SeekBar seekBar;

    int seekBarWidthLong, seekBarWidthShort;

    private int mLastX, mLastY;

    public int[][] grid_data;

    public int defaultType = 2; // 1是排班 2是抢班

    public HashMap<String, String> mapPosMem = new HashMap<String, String>();

    public ArrayList<String> listJobs = new ArrayList<>();

    private ArrangeJobManager mArangeJobManager;

    private int tmpRow;

    private boolean isEdit = false; //是否是编辑当前的班次

    public HashMap<String, String> mapPosition = new HashMap<String, String>(); //岗位的 id和name
    public HashMap<String, JSONObject> mapStaff = new HashMap<String, JSONObject>(); //灵工

    private String currentDate;

    public HashSet<String> setAlreadyMembers = new HashSet<>();

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        defaultType = getIntent().getIntExtra("type", 1);
        setContentView(R.layout.activity_arrange_job);
        CommonUtil.hideBottomUIMenu(this);
        mArangeJobManager = new ArrangeJobManager();
        mArangeJobManager.bind(this);


        mDPI = AppUtil.getdensityDpi(mContext);
        gridWidth = floatToInt(mDPI * Constant.Grid_dp_width);

        ScrollView scrollView = findViewById(R.id.scrollViewContainer);
        scrollView.getLayoutParams().height = floatToInt(AppUtil.getPixelHeight(mContext) - mDPI * (160));  // 160= topbar的高度+ 日历的高度+ 刻度线的高度

        //点击空白处关闭右边弹框
        findViewById(R.id.subScrollView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (linRightDialog.getVisibility() == View.VISIBLE) {
                    closeRightDialog();
                }
            }
        });

        linTimeLine = (FrameLayout) findViewById(R.id.lin_timeline);
        linLeft = (LinearLayout) findViewById(R.id.lin_arrLeft);
        linTable = (LinearLayout) findViewById(R.id.lin_arrRight);

        linRightDialog = (LinearLayout) findViewById(R.id.lin_right_dialog);

        seekBar = (SeekBar) findViewById(R.id.seekBar);

        int deviceWidth = 0;
        if (AppUtil.checkDeviceHasNavigationBar(mContext)) {
            deviceWidth = AppUtil.getPixelWidthIncludeVirtualKey(mContext);
        } else {
            deviceWidth = AppUtil.getPixelWidth(mContext);
        }

        seekBarWidthLong = floatToInt(deviceWidth - mDPI * (80 + 5));
        seekBarWidthShort = floatToInt(deviceWidth - mDPI * (80 + 230 + 5));

        perSeekWidth = (Constant.Grid_column_count * gridWidth + mDPI * 80 - deviceWidth) / 100;
        perSeekWidth1 = (Constant.Grid_column_count * gridWidth + mDPI * 80 + 230 * mDPI - deviceWidth) / 100;

        seekBar.getLayoutParams().width = seekBarWidthLong;

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            float tmpPer = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (isEdit) {
                    tmpPer = perSeekWidth1;
                } else {
                    tmpPer = perSeekWidth;
                }
                linTable.scrollTo((int) (i * tmpPer), 0);
                linTimeLine.scrollTo((int) (i * tmpPer), 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        initTimeLineView();

        findViewById(R.id.txt_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeRightDialog();
            }
        });

        customizeTitleView = (CustomizeTitleView) findViewById(R.id.customizeTitleView);
        customizeTitleView.setMoreListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                postData();
            }
        });

        currentDate = CommonUtil.getCurrentDate();
        getData();

        DateAdapter.setSelectDateChange(new DateAdapter.ISelectDateChange() {
            @Override
            public void invoke(DateBean date) {
                String oldDate = date.getYear() + "-" + (date.getMonth() > 9 ? date.getMonth() : "0" + date.getMonth()) + "-" + (date.getDay() > 9 ? date.getDay() : "0" + date.getDay());
                if (!oldDate.equals(currentDate)) {
                    currentDate = oldDate;
                    getData();
                }
                ((TextView) findViewById(R.id.dateYearMonth)).setText(date.getYear() + "年" + date.getMonth() + "月");
            }
        });

    }

    private void postData() {
        showLoadingDialog("请求中...");
        JSONObject allOb = new JSONObject();
        allOb.put("date", currentDate);
        JSONArray arrangeJsonArray = new JSONArray();
        for (int row = 0; row < listJobs.size(); row++) {
            for (int column = 0; column < Constant.Grid_column_count; column++) {
                if (grid_data[row][column] == 0) {
                    continue;
                }


                JSONObject joBanci = new JSONObject();
                joBanci.put("startTimeClock", column);

                joBanci.put("positionId", mapPosition.get(listJobs.get(row)));

                if (grid_data[row][column] == 1) {
                    String strMem = mapPosMem.get(row + "#" + column);
                    JSONArray jsonArrayPaipan = new JSONArray();
                    for (String str : strMem.split("#")) {
                        jsonArrayPaipan.add(str);
                    }

                    joBanci.put("normalWorkerIdList", jsonArrayPaipan);
                } else if (grid_data[row][column] == 2) {

                    JSONObject joQiangBan = new JSONObject();

                    JSONArray jsonArrayTag = new JSONArray();

                    String strMem = mapPosMem.get(row + "#" + column);

                    String[] arrData = strMem.split("#");
                    if (!StringUtil.isEmpty(arrData[2]) && !"?".equals(arrData[2])) {
                        String[] arrSkills = arrData[2].split(",");
                        for (int i = 0; i < arrSkills.length; i++) {
                            JSONObject jo = new JSONObject();
                            jo.put("tagId", arrSkills[i]);
                            jsonArrayTag.add(jo);
                        }

                        joQiangBan.put("arrangeTagDTOList", jsonArrayTag);
                    }

                    joQiangBan.put("genderRestriction", arrData[1]);
                    joQiangBan.put("totalDemand", arrData[0]);
                    joQiangBan.put("wage", arrData[3]);

                    String strAlreadyStaff = arrData[4];
                    if (!"?".equals(strAlreadyStaff)) {
                        JSONArray arrAlreadystaff = new JSONArray();
                        for (String str : strAlreadyStaff.split(",")) {
                            arrAlreadystaff.add(str);
                        }
                        joQiangBan.put("robWorkerIdList", arrAlreadystaff);
                    }

                    joBanci.put("robDemandDTO", joQiangBan);
                } else if (grid_data[row][column] == 3) {
                    String strMem = mapPosMem.get(row + "#" + column);
                    String[] arrAll = strMem.split("&");

                    String strPaiban = arrAll[0];
                    JSONArray jsonArrayPaipan = new JSONArray();
                    for (String str : strPaiban.split("#")) {
                        jsonArrayPaipan.add(str);
                    }
                    joBanci.put("normalWorkerIdList", jsonArrayPaipan);


                    String strQiangban = arrAll[1];

                    //3657069347866623046#3657078156470601740&10#1#配送飞速,味道敏锐#10#*
                    JSONObject joQiangBan = new JSONObject();
                    JSONArray jsonArrayTag = new JSONArray();
                    String[] arrData = strQiangban.split("#");
                    if (!StringUtil.isEmpty(arrData[2]) && !"?".equals(arrData[2])) {
                        String[] arrSkills = arrData[2].split(",");
                        for (int i = 0; i < arrSkills.length; i++) {
                            JSONObject jo = new JSONObject();
                            jo.put("tagId", arrSkills[i]);
                            jsonArrayTag.add(jo);
                        }
                        joQiangBan.put("arrangeTagDTOList", jsonArrayTag);
                    }

                    joQiangBan.put("genderRestriction", arrData[1]);
                    joQiangBan.put("totalDemand", arrData[0]);
                    joQiangBan.put("wage", arrData[3]);

                    String strAlreadyStaff = arrData[4];
                    if (!"?".equals(strAlreadyStaff)) {
                        JSONArray arrAlreadystaff = new JSONArray();
                        for (String str : strAlreadyStaff.split(",")) {
                            arrAlreadystaff.add(str);
                        }
                        joQiangBan.put("robWorkerIdList", arrAlreadystaff);
                    }
                    joBanci.put("robDemandDTO", joQiangBan);
                }
                if (column == Constant.Grid_column_count - 1) {
                    joBanci.put("endTimeClock", 24);
                } else {
                    ArrayList<Integer> innerlist = new ArrayList<>();
//                    if(column==0){
                    innerlist.add(column);
//                    }
                    List<Integer> list = findRigthSeriersView(innerlist, row, column);
                    joBanci.put("endTimeClock", list.get(list.size() - 1) + 1);
                    column = list.get(list.size() - 1);
                }
                arrangeJsonArray.add(joBanci);
            }

            allOb.put("arrangeInfoDTOList", arrangeJsonArray);
        }

        HttpManager.addArrange(mContext, currentDate, allOb.toJSONString(), new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(Object resonseObj) {
                showToast("数据提交成功");
                CommonUtil.hideBottomUIMenu(ArrangeJobActivity.this);
                dismissLoadingDialog();
            }

            @Override
            public void onFailure(String mes) {
                CommonUtil.hideBottomUIMenu(ArrangeJobActivity.this);
                dismissLoadingDialog();
            }
        });
    }

    private void getData() {
        if (Long.parseLong(CommonUtil.getCurrentDate().replaceAll("-", "")) > Long.parseLong(currentDate.replaceAll("-", ""))) {
            customizeTitleView.hideMoreText();
            findViewById(R.id.txt_right_save).setVisibility(View.GONE);
            findViewById(R.id.txt_delete_paiban).setVisibility(View.GONE);
        } else {
            customizeTitleView.showMoreText();
            findViewById(R.id.txt_right_save).setVisibility(View.VISIBLE);
            findViewById(R.id.txt_delete_paiban).setVisibility(View.VISIBLE);
        }
        HttpManager.getArragetList(mContext, currentDate, new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(Object resonseObj) {

                initData((JSONObject) resonseObj);


            }

            @Override
            public void onFailure(String mes) {

            }
        });
    }


    private void initData(JSONObject jsonData) {
        JSONArray jsonArray = jsonData.getJSONArray("epositionInfoVOList");

        listJobs.clear();
        mapPosition.clear();
        mapStaff.clear();
        mapPosMem.clear();

        for (int i = 0; i < jsonArray.size(); i++) {
            String name = jsonArray.getJSONObject(i).getJSONObject("positionDO").getString("name");
            listJobs.add(name);
            mapPosition.put(name, jsonArray.getJSONObject(i).getJSONObject("positionDO").getString("id"));
        }

        initLeftView();

        grid_data = new int[listJobs.size()][Constant.Grid_column_count];

        for (int row = 0; row < listJobs.size(); row++) {
            for (int column = 0; column < Constant.Grid_column_count; column++) {
                grid_data[row][column] = 0;
            }
        }

        for (int row = 0; row < jsonArray.size(); row++) {

            JSONObject jo = jsonArray.getJSONObject(row);
            JSONArray arrBanci = jo.getJSONArray("earrangeInfoVOList");

            for (int j = 0; j < arrBanci.size(); j++) {
                JSONObject objBanci = arrBanci.getJSONObject(j);
                int startTime = objBanci.getIntValue("startTimeClock");
                int endTime = objBanci.getIntValue("endTimeClock") - 1;

                int arrangeType = objBanci.getIntValue("type");

                String members = "";
                if (arrangeType == 1) {
                    JSONArray arrWorks = objBanci.getJSONArray("arrangeNormalWorkerList");
                    for (int idx = 0; idx < arrWorks.size(); idx++) {
                        String memId = arrWorks.getJSONObject(idx).getString("id");
                        if (idx == arrWorks.size() - 1) {
                            members += memId;
                        } else {
                            members += memId + "#";
                        }
                    }
                } else if (arrangeType == 2) {
                    JSONObject joQiangban = objBanci.getJSONObject("earrangeRobInfoVO");
                    JSONArray jsonArrayTagSkills = joQiangban.getJSONArray("arrangeTagDOList");

                    String strSkills = "";
                    for (int i = 0; i < jsonArrayTagSkills.size(); i++) {
                        strSkills += jsonArrayTagSkills.getJSONObject(i).getString("tagId") + ",";
                    }

                    if (strSkills.length() > 0) {
                        strSkills = strSkills.substring(0, strSkills.length() - 1);
                    } else {
                        strSkills = "?"; // ? means empty
                    }

                    JSONArray jsonArrayStaff = joQiangban.getJSONArray("arrangeRobWorkerVOList");
                    String staffIds = "";
                    for (int idx = 0; idx < jsonArrayStaff.size(); idx++) {
                        JSONObject joStaff = jsonArrayStaff.getJSONObject(idx);
                        String id = joStaff.getJSONObject("workerDO").getString("id");
                        staffIds += id + ",";
                        mapStaff.put(id, joStaff);
                    }

                    if (staffIds.length() > 0) {
                        staffIds = staffIds.substring(0, staffIds.length() - 1);
                    } else {
                        staffIds = "?";
                    }

                    int wage = (int) (joQiangban.getFloatValue("wage"));
                    members = joQiangban.getString("totalDemand") + "#" + joQiangban.getString("genderRestriction") + "#" + strSkills + "#" + wage + "#" + staffIds; //人数#性别#技能#薪资#已抢灵工ID
                } else if (arrangeType == 3) {
                    String memPaiban = "";
                    JSONArray arrWorks = objBanci.getJSONArray("arrangeNormalWorkerList");
                    if (arrWorks == null) {
                        showToast("数据有误");
                        return;
                    }
                    for (int idx = 0; idx < arrWorks.size(); idx++) {
                        String memId = arrWorks.getJSONObject(idx).getString("id");
                        if (idx == arrWorks.size() - 1) {
                            memPaiban += memId;
                        } else {
                            memPaiban += memId + "#";
                        }
                    }

                    String memQiangban = "";

                    JSONObject joQiangban = objBanci.getJSONObject("earrangeRobInfoVO");
                    JSONArray jsonArrayTagSkills = joQiangban.getJSONArray("arrangeTagDOList");

                    String strSkills = "";
                    for (int i = 0; i < jsonArrayTagSkills.size(); i++) {
                        strSkills += jsonArrayTagSkills.getJSONObject(i).getString("tagId") + ",";
                    }

                    if (strSkills.length() > 0) {
                        strSkills = strSkills.substring(0, strSkills.length() - 1);
                    } else {
                        strSkills = "?";
                    }

                    JSONArray jsonArrayStaff = joQiangban.getJSONArray("arrangeRobWorkerVOList");
                    String staffIds = "";
                    for (int idx = 0; idx < jsonArrayStaff.size(); idx++) {
                        JSONObject joStaff = jsonArrayStaff.getJSONObject(idx);
                        String id = joStaff.getJSONObject("workerDO").getString("id");
                        staffIds += id + ",";
                        mapStaff.put(id, joStaff);
                    }

                    if (staffIds.length() > 0) {
                        staffIds = staffIds.substring(0, staffIds.length() - 1);
                    } else {
                        staffIds = "?";
                    }

                    int wage = (int) (joQiangban.getFloatValue("wage"));
                    memQiangban = joQiangban.getString("totalDemand") + "#" + joQiangban.getString("genderRestriction") + "#" + strSkills + "#" + wage + "#" + staffIds; //人数#性别#技能#薪资#已抢灵工ID

                    members = memPaiban + "&" + memQiangban;
                }
                for (int idx = startTime; idx <= endTime; idx++) {
                    grid_data[row][idx] = arrangeType;
                    mapPosMem.put(row + "#" + idx, members);
                }
            }

        }
        initRightView();
    }

    private void initLeftView() {
        linLeft.removeAllViews();
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, floatToInt(mDPI * 40));
        lp.topMargin = floatToInt(0.5f * mDPI);
        for (int i = 0; i < listJobs.size(); i++) {
            TextView textView = new TextView(mContext);
            textView.setBackgroundColor(getResources().getColor(R.color.white));
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(14);
            textView.setTextColor(0xff323232);
            textView.setText(listJobs.get(i));
            linLeft.addView(textView, lp);
        }

        View viewDivider = new View(mContext);
        LinearLayout.LayoutParams lpDivier = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, floatToInt(mDPI * 0.5f));
        viewDivider.setBackgroundColor(getResources().getColor(R.color.divider_color));
        linLeft.addView(viewDivider, lpDivier);
    }

    private void initTimeLineView() {
        for (int i = 0; i < 24; i++) {
            View viewTimeSegment = LayoutInflater.from(mContext).inflate(R.layout.item_time_segment, null);

            ((TextView) viewTimeSegment.findViewById(R.id.txt_time)).setText(i + "点");

            FrameLayout.LayoutParams lpTimeLine = new FrameLayout.LayoutParams(gridWidth * 24, FrameLayout.LayoutParams.WRAP_CONTENT);
            lpTimeLine.leftMargin = gridWidth * i;
            lpTimeLine.bottomMargin = 0;

            linTimeLine.addView(viewTimeSegment, lpTimeLine);
        }

        View viewTimeSegment = LayoutInflater.from(mContext).inflate(R.layout.item_time_24, null);
        FrameLayout.LayoutParams lpTimeLine = new FrameLayout.LayoutParams(gridWidth * 24, FrameLayout.LayoutParams.WRAP_CONTENT);
        lpTimeLine.leftMargin = gridWidth * 24 - 20 * AppUtil.getdensityIntDpi(mContext);
        lpTimeLine.bottomMargin = 0;
        linTimeLine.addView(viewTimeSegment, lpTimeLine);
    }


    private void initRightView() {
        linTable.removeAllViews();

        setAlreadyMembers.clear();

        FrameLayout.LayoutParams lpRow = new FrameLayout.LayoutParams(gridWidth * 24, floatToInt(mDPI * 40));
        lpRow.topMargin = floatToInt(0.5f * mDPI);

        LinearLayout.LayoutParams lpGird = new LinearLayout.LayoutParams(gridWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        for (int row = 0; row < listJobs.size(); row++) {
            FrameLayout rowLayout = new FrameLayout(mContext);
            rowLayout.setTag(row);

            for (int col = 0; col < Constant.Grid_column_count; col++) {
                View viewGrid = new View(mContext);
                if (grid_data[row][col] == 1) {//排班
                    if (mapPosMem.containsKey(row + "#" + col)) {
                        String mems = mapPosMem.get(row + "#" + col);
                        for (String str : mems.split("#")) {
                            setAlreadyMembers.add(col + "-" + str);
                        }
                    }
                    viewGrid.setBackground(getResources().getDrawable(R.color.paiban_color));
                } else if (grid_data[row][col] == 2) {//抢班
                    viewGrid.setBackground(getResources().getDrawable(R.color.qiangban_color));
                } else if (grid_data[row][col] == 3) {
                    viewGrid.setBackground(getResources().getDrawable(R.drawable.bg_mixture));

                    if (mapPosMem.containsKey(row + "#" + col)) {
                        String mems = mapPosMem.get(row + "#" + col).split("&")[0];
                        for (String str : mems.split("#")) {
                            setAlreadyMembers.add(col + "-" + str);
                        }
                    }

                } else if (grid_data[row][col] >= 4) {
                    viewGrid.setBackground(getResources().getDrawable(R.color.tmp_color));
                } else {
                    viewGrid.setBackground(getResources().getDrawable(R.color.white));
                }

                lpGird.leftMargin = gridWidth * col;
                rowLayout.addView(viewGrid, lpGird);
            }

            linTable.addView(rowLayout, lpRow);
            rowLayout.setOnTouchListener(new View.OnTouchListener() {
                int lastGridIndex = -1;

                int lastDirecion = 0; //判断上次滑动的方向  1是向右  -1是向左

                private boolean isMove = false;

                int tmpStart = -1;

                private boolean isCanMoveInEdit = false;

                int rangeLeft = 0;
                int rangeRight = 0;

                private int getViewIndexByX(int _x) {
                    int gridIndex = (int) (_x / gridWidth);
                    if (gridIndex < 0) {
                        gridIndex = 0;
                    }
                    return gridIndex;
                }

                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int x = (int) motionEvent.getX();
                    int y = (int) motionEvent.getY();

                    int pos = (int) view.getTag();

                    switch (motionEvent.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            lastGridIndex = -1;
                            isMove = false;
                            lastDirecion = 0;
                            mLastX = x;
                            mLastY = y;

                            tmpStart = getViewIndexByX(x);

                            isCanMoveInEdit = true;

                            if (isEdit) {
                                if (tmpRow != pos) {
                                    return false;
                                }

                                String[] arr = mArangeJobManager.getTimeRange().split("#");

                                rangeLeft = Integer.parseInt(arr[0]);
                                rangeRight = Integer.parseInt(arr[1]);


                                if (grid_data[pos][tmpStart] % 4 == 2) {
                                    String[] tmp_arr = mapPosMem.get(pos + "#" + tmpStart).split("#");
                                    if (tmp_arr.length == 5) {
                                        if (!"?".equals(tmp_arr[4])) {
                                            isCanMoveInEdit = false;
                                            return true;
                                        }
                                    }
                                }

                                if (grid_data[pos][tmpStart] % 4 == 3) {
                                    String[] tmp_arr = mapPosMem.get(pos + "#" + tmpStart).split("&");
                                    String[] qbArr = tmp_arr[1].split("#");
                                    if (qbArr.length == 5) {
                                        if (!"?".equals(qbArr[4])) {
                                            isCanMoveInEdit = false;
                                            return true;
                                        }
                                    }
                                }


                                if (rangeLeft > tmpStart || rangeRight < tmpStart) {
                                    return false;
                                }

                                if (rangeLeft == tmpStart || rangeRight == tmpStart) {
                                    isCanMoveInEdit = true;
                                }

                                deleteTipView(pos);
                            }

                        case MotionEvent.ACTION_MOVE:
                            int xDiff = Math.abs(x - mLastX);
                            int yDiff = Math.abs(y - mLastY);

                            if (xDiff < yDiff) {
                                view.getParent().requestDisallowInterceptTouchEvent(false);
                                return false;
                            } else {
                                view.getParent().requestDisallowInterceptTouchEvent(true);
                                if (xDiff >= 2 * mDPI) {
                                    isMove = true;
                                    int gridIndex = getViewIndexByX(x);
                                    if (gridIndex >= Constant.Grid_column_count) {
                                        return false;
                                    }
                                    int direcion = x - mLastX > 0 ? 1 : -1;  // 1是右滑 -1是左滑
                                    View view_grid = ((ViewGroup) view).getChildAt(gridIndex);

                                    if (isEdit) {
                                        if (isCanMoveInEdit) {
                                            if (direcion != lastDirecion || lastGridIndex != gridIndex) {

//                                                if (rangeRight == rangeLeft && lastGridIndex == -1) {
////                                                    return true;
////                                                }

                                                if (gridIndex == rangeLeft && direcion == -1) {
                                                    return true;
                                                }

                                                if (gridIndex == rangeRight && direcion == 1) {
                                                    return true;
                                                }

                                                if (grid_data[pos][gridIndex] == 4) {
                                                    view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                                    grid_data[pos][gridIndex] = 0;
                                                } else if (grid_data[pos][gridIndex] > 100) {
                                                    grid_data[pos][gridIndex] = 4 + grid_data[pos][gridIndex] - 100;
                                                    view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.tmp_color));
                                                } else if (grid_data[pos][gridIndex] > 4) {
                                                    view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                                    grid_data[pos][gridIndex] = 100 + (grid_data[pos][gridIndex] % 4);
                                                } else if (grid_data[pos][gridIndex] != 1 && grid_data[pos][gridIndex] != 2 && grid_data[pos][gridIndex] != 3) {
                                                    grid_data[pos][gridIndex] = 4 + grid_data[pos][gridIndex];
                                                    view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.tmp_color));
                                                } else {
                                                    tmpStart = -1;
                                                    return false;
                                                }
                                                lastGridIndex = gridIndex;
                                                lastDirecion = direcion;
                                            }
                                        }
                                    } else {
                                        if (direcion != lastDirecion || lastGridIndex != gridIndex) {
                                            if (grid_data[pos][gridIndex] == 4) {
                                                view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                                grid_data[pos][gridIndex] = 0;
                                            } else if (grid_data[pos][gridIndex] > 4) {
                                                view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                                grid_data[pos][gridIndex] = 100 + (grid_data[pos][gridIndex] % 4);
                                            } else if (grid_data[pos][gridIndex] != 1 && grid_data[pos][gridIndex] != 2 && grid_data[pos][gridIndex] != 3) {
                                                grid_data[pos][gridIndex] = 4 + grid_data[pos][gridIndex];
                                                view_grid.setBackgroundColor(mContext.getResources().getColor(R.color.tmp_color));
                                            } else {
                                                tmpStart = -1;
                                                return false;
                                            }
                                        }
                                        lastGridIndex = gridIndex;
                                        lastDirecion = direcion;
                                    }
                                }
                            }
                            mLastX = x;
                            mLastY = y;
                            return true;

                        case MotionEvent.ACTION_UP:
                            if (tmpStart == -1) {
                                clearUselessData();
                                initRightView();
                                return false;
                            }

                            tmpRow = pos;
                            int start = -1, end = -1;

                            if (isMove) {
                                for (int i = 0; i < Constant.Grid_column_count; i++) {
                                    if (grid_data[tmpRow][i] >= 4 && grid_data[tmpRow][i] < 100) {
                                        if (start == -1) {
                                            start = i;
                                        }
                                        if (end != -1) {
                                            if (i - end > 1) { //判断是否有跳格
                                                closeRightDialog();
                                                return true;
                                            }
                                        }
                                        end = i;
                                    }
                                }
                                if (start == -1 || end == -1) {
                                    closeRightDialog();
                                    return true;
                                }

                                if (linRightDialog.getVisibility() != View.VISIBLE) {
                                    showRightDialog();
                                    mArangeJobManager.showWin(start, end, tmpRow, defaultType, "");
                                } else {
                                    mArangeJobManager.showWin(start, end, tmpRow, grid_data[tmpRow][start] % 4, "*");
                                }
                            } else {
                                int _end = getViewIndexByX(x);

                                if (isEdit) {//单击当前选择的区域没有任何反应
                                    if (isCanMoveInEdit) {
                                        addTipView(tmpRow, rangeLeft, rangeRight);
                                    }
                                    if (rangeLeft <= tmpStart && rangeRight >= tmpStart) {
                                        return false;
                                    } else {
                                        closeRightDialog();
                                        return false;
                                    }
                                }

                                List<Integer> list = findSeriersView(tmpRow, _end);
                                if (grid_data[tmpRow][_end] == 0) {
                                    return false;
                                }
                                Collections.sort(list);

                                start = list.get(0);
                                end = list.get(list.size() - 1);

                                for (int i = 0; i < list.size(); i++) {
                                    grid_data[tmpRow][list.get(i)] = 4 + grid_data[tmpRow][list.get(i)];
                                }
                                if (linRightDialog.getVisibility() != View.VISIBLE) {
                                    showRightDialog();
                                }
                                mArangeJobManager.showWin(list.get(0), list.get(list.size() - 1), tmpRow, grid_data[tmpRow][_end] % 4, mapPosMem.get(tmpRow + "#" + _end));
                                initRightView();
                            }

                            //当前已经有人抢班了 ，班次不可以编辑
                            if (grid_data[tmpRow][start] == 2 || grid_data[tmpRow][start] % 4 == 2) {
                                String[] tmp_arr = mapPosMem.get(pos + "#" + tmpStart).split("#");
                                if (tmp_arr.length == 5) {
                                    if (!"?".equals(tmp_arr[4])) {
                                        return true;
                                    }
                                }
                            }
                            if (grid_data[tmpRow][start] == 3 || grid_data[tmpRow][start] % 4 == 3) {
                                String[] tmp_arr = mapPosMem.get(pos + "#" + tmpStart).split("&");
                                String[] tmp_arr2 = tmp_arr[1].split("#");
                                if (tmp_arr2.length == 5) {
                                    if (!"?".equals(tmp_arr2[4])) {
                                        return true;
                                    }
                                }
                            }

                            if (isCanMoveInEdit) {
                                addTipView(tmpRow, start, end);
                            }


//                            View view_grid = ((ViewGroup) view).getChildAt(end);
                    }
                    return true;
                }
            });
        }

        getSeriesGrid();

        View viewDivider = new View(mContext);
        LinearLayout.LayoutParams lpDivier = new LinearLayout.LayoutParams(floatToInt(mDPI * (Constant.Grid_dp_width) * 24), floatToInt(mDPI * 0.5f));
        viewDivider.setBackgroundColor(getResources().getColor(R.color.divider_color));
        linTable.addView(viewDivider, lpDivier);
    }

    private void getSeriesGrid() {
        for (int row = 0; row < listJobs.size(); row++) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            for (int col = 0; col < Constant.Grid_column_count; col++) {
                if (col == 0) {
                    if (grid_data[row][col] > 0) {
                        list.add(col);
                    }
                    continue;
                }

                if (grid_data[row][col] == 0) {
                    if (list.size() > 0) {
                        if (mapPosMem.containsKey(row + "#" + (col - 1))) {
                            if (grid_data[row][col - 1] == 3 || grid_data[row][col - 1] % 4 == 3) {
                                addTextViewMixture(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + (col - 1)));
                            } else {
                                if (grid_data[row][col - 1] == 1 || grid_data[row][col - 1] % 4 == 1) {
                                    addTextView(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + (col - 1)).split("#").length + "人");
                                } else if (grid_data[row][col - 1] == 2 || grid_data[row][col - 1] % 4 == 2) {
                                    String arr[] = mapPosMem.get(row + "#" + (col - 1)).split("#");
                                    int already = 0;
                                    if (!"?".equals(arr[4])) {
                                        already = arr[4].split(",").length;
                                    }
                                    addTextView(row, list.get(0), list.get(list.size() - 1) + 1, already + "/" + arr[0]);
                                }
                            }
                        }
                        list.clear();
                    }
                    continue;
                }

                if (grid_data[row][col] != grid_data[row][col - 1]) {
                    if (list.size() > 0) {
                        if (mapPosMem.containsKey(row + "#" + (col - 1))) {
                            if (grid_data[row][col - 1] == 3 || grid_data[row][col - 1] % 4 == 3) {
                                addTextViewMixture(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + (col - 1)));
                            } else {
                                if (grid_data[row][col - 1] == 1 || grid_data[row][col - 1] % 4 == 1) {
                                    addTextView(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + (col - 1)).split("#").length + "人");
                                } else if (grid_data[row][col - 1] == 2 || grid_data[row][col - 1] % 4 == 2) {
                                    String arr[] = mapPosMem.get(row + "#" + (col - 1)).split("#");
                                    int already = 0;
                                    if (!"?".equals(arr[4])) {
                                        already = arr[4].split(",").length;
                                    }
                                    addTextView(row, list.get(0), list.get(list.size() - 1) + 1, already + "/" + arr[0]);
                                }
                            }
                            list.clear();
                        }
                    }

                    list.add(col);

                    if (col == Constant.Grid_column_count - 1) {
                        if (grid_data[row][col] == 3 || grid_data[row][col] % 4 == 3) {
                            addTextViewMixture(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + col));
                        } else {
                            if (grid_data[row][col] == 1 || grid_data[row][col] % 4 == 1) {
                                addTextView(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + col).split("#").length + "人");
                            } else if (grid_data[row][col] == 2 || grid_data[row][col] % 4 == 2) {
                                String arr[] = mapPosMem.get(row + "#" + col).split("#");
                                int already = 0;
                                if (!"?".equals(arr[4])) {
                                    already = arr[4].split(",").length;
                                }
                                addTextView(row, list.get(0), list.get(list.size() - 1) + 1, already + "/" + arr[0]);
                            }
                        }
                    }


                    continue;
                }

                if (mapPosMem.containsKey(row + "#" + (col - 1)) && mapPosMem.containsKey(row + "#" + col) && !mapPosMem.get(row + "#" + (col - 1)).equals(mapPosMem.get(row + "#" + col))) {
                    if (list.size() > 0) {
                        if (grid_data[row][col - 1] == 3 || grid_data[row][col - 1] % 4 == 3) {
                            addTextViewMixture(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + (col - 1)));
                        } else {
                            if (grid_data[row][col - 1] == 1 || grid_data[row][col - 1] % 4 == 1) {
                                addTextView(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + (col - 1)).split("#").length + "人");
                            } else if (grid_data[row][col - 1] == 2 || grid_data[row][col - 1] % 4 == 2) {
                                String arr[] = mapPosMem.get(row + "#" + (col - 1)).split("#");
                                int already = 0;
                                if (!"?".equals(arr[4])) {
                                    already = arr[4].split(",").length;
                                }
                                addTextView(row, list.get(0), list.get(list.size() - 1) + 1, already + "/" + arr[0]);
                            }
                        }
                        list.clear();
                    }
                    list.add(col);

                    continue;
                }
                list.add(col);
                if (col == Constant.Grid_column_count - 1) {
                    if (grid_data[row][col] == 3 || grid_data[row][col] % 4 == 3) {
                        addTextViewMixture(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + col));
                    } else {
                        if (grid_data[row][col] == 1 || grid_data[row][col] % 4 == 1) {
                            addTextView(row, list.get(0), list.get(list.size() - 1) + 1, mapPosMem.get(row + "#" + col).split("#").length + "人");
                        } else if (grid_data[row][col] == 2 || grid_data[row][col] % 4 == 2) {
                            String arr[] = mapPosMem.get(row + "#" + col).split("#");
                            int already = 0;
                            if (!"?".equals(arr[4])) {
                                already = arr[4].split(",").length;
                            }
                            addTextView(row, list.get(0), list.get(list.size() - 1) + 1, already + "/" + arr[0]);
//                            addTextView(row, list.get(0), list.get(list.size() - 1) + 1, "0/" + mapPosMem.get(row + "#" + col).split("#")[0]);
                        }
                    }
                }

            }
        }
    }

    public List<Integer> findSeriersView(int row, int gridIndex) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(gridIndex);
        findLeftSeriersView(list, row, gridIndex);

        findRigthSeriersView(list, row, gridIndex);
        return list;
    }

    private List<Integer> findLeftSeriersView(ArrayList<Integer> list, int row, int column) {
        if (column == 0) {
            return list;
        }

        int temColumn = column - 1;

        if (grid_data[row][column] != 0 && grid_data[row][column] == grid_data[row][temColumn] && mapPosMem.containsKey(row + "#" + temColumn) && mapPosMem.get(row + "#" + temColumn).equals(mapPosMem.get(row + "#" + column))) {
            list.add(temColumn);
            findLeftSeriersView(list, row, temColumn);
        }
        return list;
    }

    private List<Integer> findRigthSeriersView(ArrayList<Integer> list, int row, int column) {
        if (column == Constant.Grid_column_count - 1) {
            return list;
        }

        int temColumn = column + 1;

        if (grid_data[row][column] != 0 && grid_data[row][column] == grid_data[row][temColumn] && mapPosMem.containsKey(row + "#" + temColumn) && mapPosMem.get(row + "#" + temColumn).equals(mapPosMem.get(row + "#" + column))) {
            list.add(temColumn);
            findRigthSeriersView(list, row, temColumn);
        }
        return list;
    }

    private int floatToInt(float floatVal) {
        return (int) floatVal;
    }


    private void clearUselessData() {
        for (int i = 0; i < listJobs.size(); i++) {
            for (int j = 0; j < Constant.Grid_column_count; j++) {
                if (grid_data[i][j] > 100) {
                    grid_data[i][j] = grid_data[i][j] - 100;
                } else if (grid_data[i][j] >= 4) {
                    grid_data[i][j] = grid_data[i][j] % 4;
                }
            }
        }
    }

    private void addTipView(int row, int start, int end) {
        FrameLayout frameLayout = (FrameLayout) linTable.getChildAt(row);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(floatToInt(gridWidth / 3), FrameLayout.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams lpRight = new FrameLayout.LayoutParams(floatToInt(gridWidth / 3), FrameLayout.LayoutParams.MATCH_PARENT);
        lpRight.leftMargin = (end + 1) * gridWidth - floatToInt(gridWidth / 3);
        lp.leftMargin = start * gridWidth;

        View viewLeft = new View(mContext);
        viewLeft.setTag("leftTip");
        viewLeft.setBackgroundColor(0xff999999);
        frameLayout.addView(viewLeft, lp);

        View viewRight = new View(mContext);
        viewRight.setTag("rightTip");
        viewRight.setBackgroundColor(0xff999999);
        frameLayout.addView(viewRight, lpRight);
    }

    private void deleteTipView(int row) {
        FrameLayout frameLayout = (FrameLayout) linTable.getChildAt(row);
        frameLayout.removeView(frameLayout.findViewWithTag("leftTip"));
        frameLayout.removeView(frameLayout.findViewWithTag("rightTip"));
    }

    private void addTextView(int row, int start, int end, String txt) {
        FrameLayout frameLayout = (FrameLayout) linTable.getChildAt(row);

        FrameLayout.LayoutParams lpDivider = new FrameLayout.LayoutParams(floatToInt(mDPI * 0.5f), FrameLayout.LayoutParams.MATCH_PARENT);
        lpDivider.leftMargin = start * gridWidth;
        View view = new View(mContext);
        view.setBackgroundColor(getResources().getColor(R.color.white));
        frameLayout.addView(view, lpDivider);

        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams((end - start) * gridWidth, FrameLayout.LayoutParams.MATCH_PARENT);
        lp.leftMargin = start * gridWidth;
        TextView textView = new TextView(mContext);
        textView.setText(txt);
        textView.setTextSize(16);
        textView.setTextColor(0xffffffff);
        textView.setGravity(Gravity.CENTER);
        frameLayout.addView(textView, lp);

        FrameLayout.LayoutParams lpTopDivider = new FrameLayout.LayoutParams((end - start) * gridWidth, floatToInt(mDPI * 0.5f));
        View viewTop = new View(mContext);
        lpTopDivider.topMargin = 0;
        lpTopDivider.leftMargin = start * gridWidth;
        viewTop.setBackgroundColor(getResources().getColor(R.color.white));
        frameLayout.addView(viewTop, lpTopDivider);
    }


    private void addTextViewMixture(int row, int start, int end, String str) {
        String[] arr = str.split("&");

        FrameLayout frameLayout = (FrameLayout) linTable.getChildAt(row);

        FrameLayout.LayoutParams lpDivider = new FrameLayout.LayoutParams(floatToInt(mDPI * 0.5f), FrameLayout.LayoutParams.MATCH_PARENT);
        lpDivider.leftMargin = start * gridWidth;
        View view = new View(mContext);
        view.setBackgroundColor(getResources().getColor(R.color.white));
        frameLayout.addView(view, lpDivider);

        FrameLayout.LayoutParams lpTop = new FrameLayout.LayoutParams((end - start) * gridWidth, floatToInt(20 * mDPI));
        lpTop.leftMargin = start * gridWidth;
        TextView textViewTop = new TextView(mContext);
        textViewTop.setText(arr[0].split("#").length + " 人");

        textViewTop.setTextSize(16);
        textViewTop.setTextColor(0xffffffff);
        textViewTop.setGravity(Gravity.CENTER);
        frameLayout.addView(textViewTop, lpTop);

        FrameLayout.LayoutParams lpBottom = new FrameLayout.LayoutParams((end - start) * gridWidth, floatToInt(20 * mDPI));
        lpBottom.leftMargin = start * gridWidth;
        lpBottom.topMargin = floatToInt(20 * mDPI);
        TextView textViewBottom = new TextView(mContext);

        String tmp = str.split("&")[1].split("#")[4];
        int num = 0;
        if (!"?".equals(tmp)) {
            num = tmp.split(",").length;
        }

        textViewBottom.setText(num + "/" + arr[1].split("#")[0] + " 人");
        textViewBottom.setTextSize(16);
        textViewBottom.setTextColor(0xffffffff);
        textViewBottom.setGravity(Gravity.CENTER);
        frameLayout.addView(textViewBottom, lpBottom);
    }

    private void showRightDialog() {
        isEdit = true;
        linRightDialog.setVisibility(View.VISIBLE);
        ObjectAnimator translationX = new ObjectAnimator().ofFloat(linRightDialog, "translationX", 0, -230 * mDPI);
        AnimatorSet animatorSet = new AnimatorSet();  //组合动画
        animatorSet.playTogether(translationX); //设置动画
        animatorSet.setDuration(300);  //设置动画时间

        animatorSet.start();
        seekBar.getLayoutParams().width = seekBarWidthShort;
    }

    public void closeRightDialog() {
        isEdit = false;
        CommonUtil.hideBottomUIMenu(this);

        clearUselessData();
        initRightView();
        ObjectAnimator translationX = new ObjectAnimator().ofFloat(linRightDialog, "translationX", -230 * mDPI, 0);

        if (seekBar.getProgress() > 90) {
            int val = seekBar.getProgress() - 1;
            seekBar.setProgress(val);
        }

        AnimatorSet animatorSet = new AnimatorSet();  //组合动画
        animatorSet.playTogether(translationX); //设置动画
        animatorSet.setDuration(300);  //设置动画时间
        seekBar.getLayoutParams().width = seekBarWidthLong;
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                linRightDialog.setVisibility(View.GONE);
            }
        });

        animatorSet.start();
    }
}
